import { createRouter, createWebHashHistory } from 'vue-router'
import useLoading from "@/util/useLoading";
import axios from 'axios';
import { useStore } from 'vuex';

const { showLoad, hideLoad } = useLoading();


const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/homeView.vue'),
    },
    {
      path: '/video/:name',
      name: 'video',
      component: () => import('@/views/videoPlayer.vue'),
    },
    {
      path: "/:catchAll(.*)",
      name: "error_404",
      component: () => import("@/views/404View.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/loginView.vue"),
    }
  ],
})

router.beforeEach(async (to, from, next) => {
  showLoad();
  const store = useStore();
  const publicPages = ['/login']
  const token = store.state.Authorization; //localStorage.getItem('Authorization');

  //判断是否需要登录
  const authRequired = !publicPages.includes(to.path) && to.name !== 'error_404';

  if (authRequired && token) {
    try {
      const response = await axios.post(import.meta.env.VITE_API_HOST + '/verify.php', {}, {
        headers: {
          'Authorization': token
        }
      })
      if (response.data.status === 'success') {
        next();
      } else {
        //localStorage.removeItem('Authorization');
        sessionStorage.removeItem('user');
        next('/login');
      }
    } catch (error) {
      console.log(error);
      //localStorage.removeItem('Authorization');
      sessionStorage.removeItem('user');
      next('/login');
    }
  } else {
    next();
  }
});

router.afterEach(() => {
  hideLoad(600);
});

export default router
